import regeneratorRuntime from '../../resource/libs/runtime'
import {websocket_origin, customer_service_phone} from '../../common/config'
import {wxApiPromise, asyncReverseGeocoder, transformFromBaiduToGCJ, compare} from '../../common/utils'
import service from '../../common/service'

let app = getApp()

let regionTimer = null
let getCenterPromise = null
let key = null
Page({
  data: {
    driver_num: 0, // 候驾司机数
    origin: '', // 出发地
    destination: '', // 目的地
    
    coupon_tip: '使用优惠券',
    coupon: '', // 已选的优惠券
    coupon_id: '', // 已选的优惠券 id
    if_coupon_used: false, // 选中的优惠券是否已使用
    coupon_init: false, // 是否已加载优惠券列表
    coupon_list: [],
    
    money: 0, // 预估价格
    init: false, // 首页是否已初始化完成
    submit_loading: false,
    
    latitude: '',
    longitude: '',
    allMarkers: [],
    scale: '',
    setting: {
      showLocation: true
    }
  },
  
  async onLoad(query) { 
    this.mapContext = wx.createMapContext('index-map', this)
    let initLocation
    
    if(query.hotel_id){
      let hotelLocation = await this.getHotelLocation(query.hotel_id)
      if (hotelLocation && hotelLocation.lat && hotelLocation.lng){
        initLocation = {
          latitude: hotelLocation.lat,
          longitude: hotelLocation.lng
        }
      }
    }
    if(!initLocation){
      if (query.lat && query.lng) {
        initLocation = {
          latitude: query.lat,
          longitude: query.lng
        }
      }
    }
    await this.init(initLocation)
    app.updateGlobalData({
      hotel_id: query.hotel_id || ''
    })
    wx.onSocketOpen(() => {
      // debug
      app.alert('wss 已打开')
      // debug
      app.global_data.socket_closed = false
      wx.onSocketMessage(async (res) => {
        let res_data = JSON.parse(res.data)
        let {client_id, id, u_id} = res_data.data
        if (client_id) {
          let r = await service.postPromise('gateway/bind', {client_id})
          // debug
          if (r && typeof r !== 'number') {
            app.alert('wss 已建立通讯关系')
          }
          // debug
        }
        if (id) {
          // debug
          app.alert('wss 接收到接单消息')
          // debug
          let r = await wxApiPromise(wx.sendSocketMessage, {
            data: JSON.stringify({type: "MINIPush", id, u_id})
          })
          if (r) {
            let route = getCurrentPages().pop().route
            let detail_route = 'pages/mine/journey/detail/index'
            let url = `/${detail_route}?id=${id}`
            if (route === detail_route) {
              wx.redirectTo({url})
            } else {
              wx.navigateTo({url})
            }
          }
        }
      })
    })
    wx.onSocketClose(() => {
      // debug
      app.alert('wss 已关闭')
      // debug
      app.global_data.socket_closed = true
      if (app.global_data.app_show) {
        wx.connectSocket({
          url: websocket_origin
        })
      }
    })
    // 确保首次连接时 token 是有效的
    wx.connectSocket({
      url: websocket_origin
    })
  },
  onUnload() {
    // 防止因为授权而出现两次加载首页时，执行了 onShow 回调
    app.updateGlobalData({origin: '', destination: ''})
  },
  async onShow() {
    let {origin, destination, start, o_location} = app.global_data
    if (origin && origin !== this.data.origin) {
      this.init({
        longitude: o_location.longitude,
        latitude: o_location.latitude
      })
      this.setData({origin})
      this.getInfo()
    }
    if (destination !== this.data.destination) {
      this.setData({destination})
      // 如果未获取价格表，先获取再计算预估价格
      if (!start.length) {
        wx.showLoading({
          title: '数据加载中'
        })
        let res = await service.getPromise('SystemPrice/initPrice/mini')
        wx.hideLoading()
        if (typeof res === 'number') {
          return
        }
        if (res) {
          let {interval, start, wait} = res.data
          app.updateGlobalData({interval, start, wait})
        }
      }
      await app.calPrice()
      let {origin_money, km_money} = app.global_data
      this.setData({money: origin_money + km_money})
    }
    // 重新获取优惠券列表
    if (this.data.if_coupon_used) {
      this.setData({
        coupon: '',
        coupon_id: '',
        if_coupon_used: false,
        coupon_init: false,
        coupon_list: []
      })
      service.getPromise('tickets/user').then(res => {
        if (!res || typeof res === 'number') {
          return
        }
        this.setData({coupon_list: res.data, coupon_init: true})
      })
    }
  },
  async onPullDownRefresh() {
    await this.init()
    wx.stopPullDownRefresh()
  },
  async getHotelLocation(hotel_id){
    let res = await service.getPromise('hotel/location', {
      hotel_id: hotel_id
    })
    return res.data
  },
  
  // 初始化
  async init(location) {
    if(!location){
      // 首先，先获取用户当前位置的经纬度
      location = await service.asyncGetLocation(true)
      this.firstDrag = true
    }else{
      this.firstDrag = false
      this.mapContext.moveToLocation(location)
    }
    this.setData({
      latitude: location.latitude,
      longitude: location.longitude
    })
    
    if (location) {
      this.updateZhAndDrivers(location)
      this.getInfo(location)
    }
  },
  
  async bindRegionChange({type, causedBy}) {
    if (type !== 'end') return
    let mapContext = this.mapContext
    switch (causedBy) {
      case 'drag':
        this.firstDrag = false
        let location = await wxApiPromise(mapContext.getCenterLocation)
        this.updateZhAndDrivers(location)
        break
      case 'scale':
        if (this.firstDrag) {
          mapContext.moveToLocation({
            latitude: this.data.latitude,
            longitude: this.data.longitude
          })
        }
        break
      case 'update':
        if(this.timer) return
        mapContext.moveToLocation({
          latitude: this.data.latitude,
          longitude: this.data.longitude
        })
        this.timer = setTimeout(() => {
          this.timer = null
        }, 1000)
    }
  },
  
  updateMarkers(markers) {
    let allMarkers = markers.map(marker => {
      return {
        id: marker.id,
        latitude: marker.latitude,
        longitude: marker.longitude,
        iconPath: '/resource/images/blue.png',
        width: 32,
        height: 32
      }
    })
    let flag = compare(this.data.allMarkers, allMarkers)
    if (!flag) {
      this.setData({
        allMarkers: allMarkers
      })
    }
  },
  
  updateZhAndDrivers(location) {
    let latLng = {
      latitude: location.latitude,
      longitude: location.longitude
    }
    asyncReverseGeocoder({
      location: latLng
    }).then(res => {
      if (res) {
        let {address_component, formatted_addresses} = res.result
        let origin = formatted_addresses.recommend
        let o_region = [
          address_component.province,
          address_component.city,
          address_component.district
        ]
        app.updateGlobalData({origin, o_region, o_location: latLng})
        this.setData({origin})
      }
    })
    this.getInfo(location)
    
    this.getDrivers(latLng)
    
  },
  
  async getInfo(location) {
    location = location || app.global_data.o_location
    let res = await service.getPromise('SystemPrice/initIndex/mini', {
      lat: location.latitude,
      lng: location.longitude
    })
    if (typeof res === 'number') {
      return
    }
    if (res) {
      let {drivers, interval, tickets} = res.data
      app.updateGlobalData({interval})
      await app.calPrice()
      let {origin_money, km_money} = app.global_data
      this.setData({
        init: true,
        driver_num: drivers,
        money: origin_money + km_money,
        coupon_list: tickets,
        coupon_tip: '使用优惠券',
        coupon_init: true
      })
    }
  },
  
  async getDrivers({latitude, longitude}) {
    let res = await service.getPromise('drivers/nearby', {
      lat: latitude,
      lng: longitude
    })
    let markers = []
    if (res && typeof res !== 'number') {
      let {data} = res
      if (!Array.isArray(data)) {
        data = []
      }
      markers = data.map(marker => {
        let location = marker.location || {}
        let {latitude, longitude} = transformFromBaiduToGCJ(location.lat, location.lng)
        return {
          id: parseInt(marker.id),
          latitude: latitude,
          longitude: longitude,
          state: marker.state
        }
      }).filter(marker => marker.state === 1)
    }
    this.updateMarkers(markers)
  },
  
  async submit() {
    if (!app.global_data.phone) {
      wx.navigateTo({
        url: '/pages/mine/index'
      })
    } else if (!this.data.submit_loading) {
      this.setData({submit_loading: true})
      let t_id = this.data.coupon_id
      let { origin, o_location, destination, d_location, hotel_id} = app.global_data
      let res = await service.postPromise('order/mini/save', {
        start: origin,
        start_lat: o_location.latitude,
        start_lng: o_location.longitude,
        end: destination,
        end_lat: d_location.latitude,
        end_lng: d_location.longitude,
        t_id,
        hotel_id: hotel_id
      })
      this.setData({submit_loading: false})
      if (!res) {
        return
      }
      if (typeof res === 'number') {
        await wxApiPromise(wx.showModal, {
          title: '下单失败',
          showCancel: false
        })
        return
      }
      if (t_id) {
        this.setData({if_coupon_used: true})
      }
      wx.navigateTo({
        url: '/pages/mine/journey/detail/index?id=' + res.data.id
      })
    }
  },
  
  originTap() {
    wx.navigateTo({
      url: '/pages/site/index?type=origin'
    })
  },
  destinationTap() {
    wx.navigateTo({
      url: '/pages/site/index?type=destination'
    })
  },
  async couponTap() {
    let coupon_list = this.data.coupon_list
    if (coupon_list.length === 0) {
      this.setData({
        coupon_tip: '暂无优惠券'
      })
      return
    }
    let list = []
    coupon_list.forEach(item => {
      list.push(item.money + '元' + item.name)
    })
    list.push('不使用优惠券')
    let res = await wxApiPromise(wx.showActionSheet, {
      itemList: list
    })
    if (res) {
      let {tapIndex} = res
      let if_last_index = tapIndex === list.length - 1
      this.setData({
        coupon: if_last_index ? '' : list[tapIndex],
        coupon_id: if_last_index ? '' : coupon_list[tapIndex].id
      })
    }
  },
  questionTap() {
    wx.navigateTo({
      url: '/pages/question/index'
    })
  },
  
  footerTap({currentTarget}) {
    let index = currentTarget.dataset.index
    if (index === 0) {
      wx.navigateTo({
        url: '/pages/mine/index'
      })
    } else {
      wx.showActionSheet({
        itemList: customer_service_phone,
        success({tapIndex}) {
          wx.makePhoneCall({
            phoneNumber: customer_service_phone[tapIndex]
          })
        }
      })
    }
  }
})
